package com.project.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;

public class TestServlet extends HttpServlet {

    public TestServlet(){
        System.out.println("产生TestServlet");
    }
    @Override
    public void init() throws ServletException {
        System.out.println("重写init方法，完成初始化");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        this.doPost(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //设置请求信息的编码集，只对POST有效
        req.setCharacterEncoding("utf-8");

        //设置响应信息的MIME类型和编码集（防止中文乱码）
        resp.setContentType("text/html;charset=utf-8");

        //根据表单名，得到表单值
        String name = req.getParameter("name");

        //得到多个同名的键值对（复选框）
        String[] likeArray = req.getParameterValues("like");

        //得到打印的字符流，可以像客户端输出文本数据
        PrintWriter w = resp.getWriter();
        w.print("hello 中国！ 表单数据:name="+name+"<br>");
        w.print(Arrays.toString(likeArray));

        //得到写入的字节流，可以向客户端发送二进制数据
        OutputStream out = resp.getOutputStream();

    }
}
